<template>
  <div class="bar-chart-wrapper">
    <!-- <button type="button" @click="refreshData">刷新</button> -->
    <BaseEcharts :chartData="realTimeData" ref="bar" height="200px" />
  </div>
</template>

<script>
import BaseEcharts from './echart.vue'
import dayjs from 'dayjs'
export default {
  name: 'BarChart',
  components: {
    BaseEcharts
  },
  data() {
    return {
      barData: [
        { label: '20时', time: 20, value: 0, maxValue: 2536, minValue: 1 },
        { label: '19时', time: 19, value: 0, maxValue: 2180, minValue: 1 },
        { label: '18时', time: 18, value: 0, maxValue: 2791, minValue: 1 },
        { label: '17时', time: 17, value: 0, maxValue: 2812, minValue: 1 },
        { label: '16时', time: 16, value: 0, maxValue: 3949, minValue: 1 },
        { label: '15时', time: 15, value: 0, maxValue: 3785, minValue: 1 },
        { label: '14时', time: 14, value: 0, maxValue: 3524, minValue: 1 },
        { label: '13时', time: 13, value: 0, maxValue: 1216, minValue: 1 },
        { label: '12时', time: 12, value: 0, maxValue: 3221, minValue: 1 },
        { label: '11时', time: 11, value: 0, maxValue: 4282, minValue: 1 },
        { label: '10时', time: 10, value: 0, maxValue: 3798, minValue: 1 },
        { label: '09时', time: 9, value: 0, maxValue: 3010, minValue: 1 }
      ],
      realTimeData: [],
      intervalIns: null
    }
  },
  mounted() {
    this.refreshData()
  },
  methods: {
    refreshData() {
      this.intervalIns && clearInterval(this.intervalIns)
      this.getRealTimeData()
      this.intervalIns = setInterval(this.getRealTimeData.bind(this), 1000 * 60 * 1)
    },
    getRealTimeData() {
      const curHour = dayjs().hour()
      this.realTimeData = this.barData.map(item => {
        const itemHour = item.time
        const value = itemHour > curHour ? 0 : itemHour == curHour ? this.getValueByMinute(item) : item.maxValue
        return {
          ...item,
          value,
          value2: value,
          maxValue2: item.maxValue,
          highLight: itemHour == curHour
        }
      })
    },
    getValueByMinute({ maxValue }) {
      const minuteNow = dayjs().minute()
      const minuteVal = (maxValue / 60) * minuteNow
      return isNaN(minuteVal) ? 0 : +this.toFixed(minuteVal, 0)
    },
    toFixed(n, fixedNum = 2) {
      return ~~(Math.pow(10, fixedNum) * n) / Math.pow(10, fixedNum)
    }
  },
  destroyed() {
    clearInterval(this.intervalIns)
  }
}
</script>

<style scoped>
.bar-chart-wrapper {
  /* background-color: #1b2e4a;
  width: 1366px;
  height: 768px; */
}
</style>
